package com.lswms.modules.lswms.service.impl.base;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.common.utils.ConvertUtils;
import com.lswms.common.utils.TreeUtils;
import com.lswms.modules.lswms.dao.base.SkucategoryDao;
import com.lswms.modules.lswms.dto.base.SkucategoryDTO;
import com.lswms.modules.lswms.entity.base.SkucategoryEntity;
import com.lswms.modules.lswms.service.base.SkucategoryService;

/**
 * 物料类别
 *
 * @author DX sunlightcs@gmail.com
 * @since 1.0.0 2021-07-23
 */
@Service
public class SkucategoryServiceImpl extends CrudServiceImpl<SkucategoryDao, SkucategoryEntity, SkucategoryDTO> implements SkucategoryService {

    @Override
    public QueryWrapper<SkucategoryEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<SkucategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Override
	public List<SkucategoryDTO> getAllSkucategoryList(Integer type) {
		List<SkucategoryEntity> menuList = baseDao.selectList(null);
		List<SkucategoryDTO> dtoList = ConvertUtils.sourceToTarget(menuList, SkucategoryDTO.class);

		return TreeUtils.build(dtoList);
	}

	@Override
	public String getLongSort(String sort) {
		
		if (StringUtils.isNotBlank(sort)) {
			List<SkucategoryEntity> list = baseDao.selectList(null);

			for (SkucategoryEntity skucategoryEntity : list) {
				String temSort = skucategoryEntity.getCategorykey();
				if (sort.equals(temSort)) {
					Long pid = skucategoryEntity.getPid();
					sort = getpreSort(list, pid) + sort + "#";
				}
			}
		}
		return sort;
	}
	
	private String getpreSort(List<SkucategoryEntity> list, Long pid) {
		String str = "";

		for (SkucategoryEntity skucategoryEntity : list) {
			Long id = skucategoryEntity.getId();
			if (pid.equals(id)) {
				String tmpCategorykey = skucategoryEntity.getCategorykey();
				Long tmpPid = skucategoryEntity.getPid();
				str = tmpCategorykey + "#" + str;
				String tmp = getpreSort(list, tmpPid);
				if (StringUtils.isNoneBlank(tmp)) {
					str = tmp + str;
				}
			}
		}
		return str;
	}

}